import React from 'react';
import './addStore.less';
import region from '../../../common/region';
import {browserHistory,Link} from 'react-router';
import { Form, Button, Input, Select, message,  Cascader,Modal,TimePicker,Checkbox,Row,Col,DatePicker } from 'antd';
import moment from 'moment';
import $ from 'jquery';
import config from '../../../config/config';
const allRouter=config.router;
const FormItem = Form.Item;
const Option = Select.Option;
const token = sessionStorage.getItem('token');
class AddStore extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            time1:0,//时间选择器1选择的时间
            visible2:false,//增加关联门店模态框
            storeNameList:[],//所有门店列表
            selectedStoreList:[],//已选择的门店列表把初始值赋值一份给保存
            initialSelectedStoreList:[],//保存最开始的已关联门店的初始值，如果模态框点击取消则不改变，如果点击确定，再把数据赋值
            justShowingStore:[],//只是为了展示，因为门店列表的数据为ID
            handnamed:false,//门店是否重名
        }
        this.saveData = this.saveData.bind(this);
        this.cancelSave = this.cancelSave.bind(this);
    }
    componentWillMount() {
        this.getStoreList();
    }
    componentDidMount() {
        this.handleRegion();
        //接受前页面点击编辑时传来的参数
        // console.log(this.props.location);
        if(this.props.params.storeId !== "0"){
            let url=allRouter.patientOrigin+'/cmmuseum/one/'+this.props.params.storeId;
            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:data=>{
                    console.log(data);
                    //把已经关联的门店赋值给到模态框显示，
                    this.setState({
                        selectedStoreList:data.cmmuseum.managershops
                    },()=>{
                        this.changeToWord(this.state.selectedStoreList);
                        console.log(this.state.selectedStoreList);
                    });
                    //保存最开始的已关联门店的初始值
                    let initName=[];
                    data.cmmuseum.managershops.map(item=>{
                        initName.push(item);
                    });
                    this.setState({
                        initialSelectedStoreList:initName
                    });
                    let values=data.cmmuseum;
                    if(data.code===200){
                        this.props.form.setFieldsValue({
                            storeid:values.name,
                            storeAttribute:values.type,
                            storePhone:values.phone,
                            address1:values.address.split(","),
                            address2:values.addressdetail,
                            timePicker1:values.starttime? moment(values.starttime, 'HH:mm:ss') : null,//时间反格式化
                            timePicker2:values.endtime?moment(values.endtime, 'HH:mm:ss') : null,//时间反格式化
                            peopleCount:values.limitnumber,
                            username:values.managername,
                            phone:values.managerphone,
                            gender:values.managersex,
                            identification:values.managercardid,
                            email:values.manageremail,
                            uname:values.manageraccount,
                            password:values.managerpassword,
                            confirmPassword:values.managerpassword,
                            birthday:values.birthday? moment(values.birthday) : undefined,
                        });
                    }else{
                        console.log("获取该门店信息出错");
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        }
    }
    //处理省市区数据
    handleRegion() {
        const setOptions = arr => {
            arr.map((item, key) => {
                item.value = item.name;
                item.label = item.name;
                if (item.child) {
                    item.children = item.child;
                    setOptions(item.children);
                }
            });
        };
        setOptions(region);
        this.setState({
            region
        });
    }
    //获取门店列表
    getStoreList() {
        let url=allRouter.patientOrigin+'/cmmuseum/list';
        //console.log(url);
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log(data);
                if(data.code===200){
                    if (data.cmmuseums.length > 0) {
                        data.cmmuseums.forEach((ele, i) => {
                            ele.index= i + 1;
                        });
                    }
                    this.setState({
                        storeNameList:data.cmmuseums
                    })
                }else{
                    console.log("获取门店列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    //把ID转换成汉字显示
    changeToWord(selectedStore){
        let justShowingStore=[];
        if(selectedStore.length){
            selectedStore.map(ele=>{
                this.state.storeNameList.map(item=>{
                    if(item._id==ele){
                        justShowingStore.push(item.name);
                    }
                })
            });
            this.setState({
                justShowingStore
            })

        }
    }
    //保存门店
    saveData(){
        this.props.form.validateFields((err,fieldsValue)=> {
            console.log(fieldsValue);
            if (!err) {
                if (fieldsValue.password != fieldsValue.confirmPassword) {
                    //  this.props.form.setFields({
                    //     password: {value: fieldsValue.password, errors: '两次输入的密码不一致，请再次输入'},
                    //     confirmPassword: {value: fieldsValue.confirmPassword, errors: '两次输入的密码不一致，请再次输入'},
                    // });
                    message.info('两次输入的密码不一致，请再次输入',2)
                    return;
                }
                if(this.state.handnamed){
                    message.error('该门店名称已存在!',1);
                    return;
                }
                if(fieldsValue['timePicker2'].isBefore(fieldsValue['timePicker1'])){
                    message.error('该门店预约时间,开始时间必须小于结束时间',1);
                    return;
                }
                console.log();
                const values = {
                    ...fieldsValue,
                    'timePicker1': fieldsValue['timePicker1'].format('HH:mm:00'),
                    'timePicker2': fieldsValue['timePicker2'].format('HH:mm:00'),
                    'birthday': fieldsValue['birthday']?fieldsValue['birthday'].format('YYYY-MM-DD'):'',
                };
                console.log(values);

                //发送Ajax请求，post，增加门店信息
                let url=allRouter.patientOrigin+'/cmmuseum/save';
                //即是编辑状态
                if(this.props.params.storeId !== "0"){
                    let url=allRouter.patientOrigin+'/cmmuseum/update';
                   // console.log(url);
                    $.ajax({
                        url: url,
                        type: "post",
                        async: true,
                        traditional: true,
                        headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                        data: {
                            name:values.storeid,
                            type:values.storeAttribute,
                            phone:values.storePhone,
                            address:values.address1,
                            addressdetail:values.address2,
                            starttime:values.timePicker1,
                            endtime:values.timePicker2,
                            limitnumber:values.peopleCount,
                            managername:values.username,
                            managerphone:values.phone,
                            managersex:values.gender,
                            managercardid:values.identification,
                            manageremail:values.email,
                            manageraccount:values.uname,
                            managerpassword:values.password,
                            managershops:this.state.initialSelectedStoreList,
                            id:this.props.params.storeId,
                            birthday:values.birthday,
                            jurisdiction:["031", "021", "022", "024", "027", "026", "028", "0121", "0122", "0123", "0124", "0125", "0126", "0127", "0128", "012", "030", "02", "根"],
                        },
                        success:data => {
                            console.log(data);
                            if(data.code===200){
                                message.info('更改门店信息成功',);
                                browserHistory.push('/storeManage');
                            }else{
                                message.info('更改门店信息错误');
                            }
                        },
                        error:err=>{
                            console.log(err);
                        }
                    });
                    return;
                }
                //即是新增状态
                $.ajax({
                    url: url,
                    type: "post",
                    async: true,
                    traditional: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data: {
                        name:values.storeid,
                        type:values.storeAttribute,
                        phone:values.storePhone,
                        address:values.address1,
                        addressdetail:values.address2,
                        starttime:values.timePicker1,
                        endtime:values.timePicker2,
                        limitnumber:values.peopleCount,
                        managername:values.username,
                        managerphone:values.phone,
                        managersex:values.gender,
                        managercardid:values.identification,
                        manageremail:values.email,
                        manageraccount:values.uname,
                        managerpassword:values.password,
                        managershops:this.state.initialSelectedStoreList,
                        state:'启用',
                        birthday:values.birthday,
                        jurisdiction:["031", "021", "022", "024", "027", "026", "028", "0121", "0122", "0123", "0124", "0125", "0126", "0127", "0128", "012", "030", "02", "根"],
                    },
                    success:data => {
                        console.log(data);
                        if(data.code===200){
                            message.info('门店增加成功',);
                            browserHistory.push('storeManage');
                        }else{
                            message.error(data.mes);
                            // this.props.form.setFields({
                            //     storeid: { value: data.name,errors: [new Error('门店名称已存在，请修改')] }
                            // })
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
            }
        })
    }
    //取消保存
    cancelSave(){
        Modal.confirm({
            title:'取消保存',
            content:'确认取消保存并返回门店列表页面吗？',
            onCancel:()=>{
               // console.log('取消')
            },
            onOk:()=>{
                browserHistory.push('storeManage');
            }
        })
    }
    //显示关联门店模态框
    showModal2() {
        this.setState({
            visible2: true,
        });
    }
    //关联所属门店
    handleOk2() {
        // console.log(this.state.selectedStoreList);
        // console.log(typeof(this.state.selectedStoreList));
        this.setState({
            initialSelectedStoreList:this.state.selectedStoreList,
            visible2: false,
        },()=>{
            // console.log(this.state.initialSelectedStoreList);
            // console.log(typeof(this.state.initialSelectedStoreList));
        })

    }
    //取消关联所属门店
    handleCancel2() {
        this.setState({
            visible2: false,
            selectedStoreList:this.state.initialSelectedStoreList
        },()=>{
            this.changeToWord(this.state.selectedStoreList);
        });
    }
    //所属门店模态框变化函数
    handleBelongedStoreChange(checkedValues){
        console.log(checkedValues);
        this.setState({
            selectedStoreList:checkedValues
        },()=>{
            this.changeToWord(this.state.selectedStoreList);
        })
    }
    //绑定手机号输入框的onChange事件，设置用户名
    changUserName(e){
        // console.log(e.target.value);
        this.props.form.setFieldsValue({
            uname: e.target.value
        })
    }

    //验证门店名称是否重复
    hadnamed(e){
        console.log(e.target.value);
        let scheduleName = e.target.value;
        let url=allRouter.patientOrigin+'/cmmuseum/hadnamed';
        $.ajax({
            url: url,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data: {
                name:e.target.value
            },
            success:data => {
                console.log(data);
                if(data.code===201){
                    this.props.form.setFields({
                        storeid: { value: scheduleName,errors: [new Error(data.mes)] }
                    });
                    this.setState({
                        handnamed:true
                    })
                }else{
                    this.setState({
                        handnamed:false
                    })
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }

    //验证管理员手机号是否重复
    hadnamedPhone(e){
        console.log(e.target.value);
        let scheduleName = e.target.value
        let url=allRouter.patientOrigin+'/doctor/alreadyregister';
        $.ajax({
            url: url,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data: {
                managerphone:e.target.value
            },
            success:data => {
                console.log(data);
                if(data.code===201){
                    this.props.form.setFields({
                        phone: { value: scheduleName,errors: [new Error(data.mes)] }
                    })
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }


    //时间选择器1变化触发的函数value
    handleTimePicker1(value,valueString){
        let time1=valueString.slice(0, 2);
        this.setState({
            time1,
        })
    }
    //时间选择器禁用部分时间
    disabledHours(){
        let hours=[];
        for(let i=0;i<24;i++){
            hours.push(i);
        }
        let hours2=hours.slice(0,this.state.time1);
        return hours2;
    }
    //生日禁用
    disabledDate(val) {
        if (val) {
            return val.valueOf() > Date.now();
        } else {
            return false;
        }
    }
    render() {
        //console.log(this.state.paths);
        const config = {
            rules: [{ type: 'object', required: true, message: '请选择时间' }],
        };
        const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
        const { getFieldDecorator } = this.props.form;
        return (
            <div className='container'>
                <div className='add-store-box'>
                    <div className="show-template">
                        <span>*{this.props.params.storeId != "0"?"编辑":"新增"}门店信息</span>
                    </div>
                    <h2>门店信息</h2>
                    <div className="my-border"></div>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="门店名称" style={{ display: 'inline-block', width: '40%' }} >
                            {getFieldDecorator('storeid', {
                                rules: [
                                    { required: true, message: '门店名称不能为空' },
                                    { max: 40, message: '门店名称不能超过40字' },
                                    { pattern: /^([\u4e00-\u9fa5]|[a-zA-Z0-9])+$/, message: '请输入中文或英文或数字' }
                                ],
                            })(
                                <Input placeholder="请输入门店名称" onKeyUp={this.hadnamed.bind(this)}/>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="门店属性" style={{ display: 'inline-block', width: '30%' }} >
                            {getFieldDecorator('storeAttribute', {
                                rules:[
                                    { required: true, message: '门店属性不能为空' },
                                ]
                            })(
                                <Select style={{ width: "150px" }} placeholder="请选择门店属性">
                                    <Option value="中药房">中药房</Option>
                                    <Option value="西药房">西药房</Option>
                                    <Option value="中医药房门诊">中医药房门诊</Option>
                                    <Option value="西医药房门诊">西医药房门诊</Option>
                                    <Option value="中西医结合门诊">中西医结合门诊</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="门店座机" style={{ display: 'inline-block', width: '30%' }} >
                            {getFieldDecorator('storePhone',{
                                rules: [{ pattern:/^0\d{2,3}-[1-9]\d{6,7}$/,message:'请输入3或4位区号-座机号码' }],
                            })(
                                <Input placeholder="请输入门店座机" />
                            )}
                        </FormItem>
                    </div>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="门店地址" hasFeedback style={{ display: 'inline-block', width: '400px' }} >
                            {getFieldDecorator('address1', {
                                rules: [{ required: true, type: 'array', message: '请选择收货地址所在的地区！' }],
                            })(
                                <Cascader options={region} placeholder="请选择省市区" style={{ width: '230px' }}/>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} style={{ display: 'inline-block', width: '600px' }} >
                            {getFieldDecorator('address2', {
                                rules: [{ required: true, message: '详细地址不能为空' },
                                    { max: 200, message: '最多不能超过200个字符' },
                                    { pattern: /^\S+$/, message: '请不要输入空格'}],

                            })(
                                <Input placeholder="请输入详细地址" />
                            )}
                        </FormItem>
                    </div>
                    <h2 style={{marginTop:"28px"}}>预约设置</h2>
                    <div className="my-border"></div>
                    <div className='storeRow my-clear-fix'>
                        <FormItem style={{ display: 'inline-block', width: '20%' }}
                                  {...{ labelCol: { span: 10 }, wrapperCol: { span: 12 } }}
                                  label="预约起止："
                        >
                            {getFieldDecorator('timePicker1', config)(
                                <TimePicker format="HH:mm:00" placeholder="开始时间" minuteStep={30} onChange={this.handleTimePicker1.bind(this)}/>
                            )}
                        </FormItem>
                        _____&nbsp;
                        <FormItem style={{ display: 'inline-block', width: '40%' }}
                                  {...{ labelCol: { span: 2 }, wrapperCol: { span: 18 } }}
                        >
                            {getFieldDecorator('timePicker2',config)(
                                <TimePicker format="HH:mm:00" placeholder="结束时间" minuteStep={30} disabledHours={this.disabledHours.bind(this)}/>
                            )}
                        </FormItem>
                        <div style={{ display: 'inline-block', float:'right',marginRight:'17%' }}>
                            时间间隔：30分钟
                        </div>
                    </div>
                    <div className='storeRow'>
                        <FormItem {...{ labelCol: { span: 5 }, wrapperCol: { span: 19 } }} label="每段时间医生最多预约人数" style={{ display: 'inline-block', width: '100%' }} >
                            {getFieldDecorator('peopleCount', {
                                rules: [{ required: true, message: '请选择人数' }]
                            })(
                                <Select style={{ width: "100%" }} placeholder='请选择人数'>
                                    <Option value={0}>0个（表示每个时间段可接诊任意人数）</Option>
                                    <Option value={1}>1个</Option>
                                    <Option value={2}>2个</Option>
                                    <Option value={3}>3个</Option>
                                    <Option value={4}>4个</Option>
                                    <Option value={5}>5个</Option>
                                </Select>
                            )}
                        </FormItem>
                    </div>
                    <h2 style={{marginTop:"28px"}}>超级管理员信息录入</h2>
                    <div className="my-border"></div>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="姓名" style={{ display: 'inline-block', width: '30%' }} >
                            {getFieldDecorator('username', {
                                rules: [{ required: true, message: '姓名不能为空' },
                                    { max: 20, message: '最多不能超过20个字' },
                                    { pattern: /^([\u4e00-\u9fa5]|[a-zA-Z0-9])+$/, message: '请输入中文或英文或数字' }]
                            })(
                                <Input placeholder="请输入姓名" />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="电话号码" style={{ display: 'inline-block', width: '40%' }} >
                            {getFieldDecorator('phone', {
                                rules: [{ required: true, pattern: /^(1[34578]\d{9})$/, message: '请输入正确的手机号' }]
                            })(
                                <Input placeholder="请输入电话号码" onKeyUp={this.hadnamedPhone.bind(this)}  onChange={this.changUserName.bind(this)}/>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="性别" style={{ display: 'inline-block', width: '30%' }} >
                            {getFieldDecorator('gender', {
                                rules: [{ required: true, message: '请选择性别' }]
                            })(
                                <Select style={{ width: "100%" }} placeholder="请选择">
                                    <Option value="1">男</Option>
                                    <Option value="2">女</Option>
                                </Select>
                            )}
                        </FormItem>
                    </div>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="身份证" style={{ display: 'inline-block', width: '30%' }} >
                            {getFieldDecorator('identification', {
                                rules: [{ required: true, pattern: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X|x)$/, message: '请输入18位身份证号' }]
                            })(
                                <Input placeholder="请输入18位身份证号" />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="负责人邮箱" style={{ display: 'inline-block', width: '40%' }}>
                            {getFieldDecorator('email', {
                                rules: [{
                                    type: 'email', message: '请输入正确格式邮箱',
                                }],
                            })(
                                <Input />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="出生年月"  style={{ display: 'inline-block', width: '30%' }}>
                            {getFieldDecorator('birthday',{
                            })(
                                <DatePicker  format="YYYY-MM-DD" disabledDate={(val) => this.disabledDate(val)} style={{ width: '100%' }}/>
                            )}
                        </FormItem>
                    </div>

                    <h2 style={{marginTop:"28px"}}>超级管理员帐号设置</h2>
                    <div className="my-border"></div>
                    <div className="storeRow">
                        <FormItem {...formItemLayout} label="登录账号" style={{ display: 'inline-block', width: '33%' }} >
                            {getFieldDecorator('uname', {
                                rules: [{ required: true, message: '登录账号不能为空' }],
                            })(
                                <Input placeholder="请输入用户名" disabled={true}/>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="设置密码" style={{ display: 'inline-block', width: '33%' }} >
                            {getFieldDecorator('password', {
                                rules: [
                                    { required: true, whitespace: true, message: '密码不能为空' },
                                    { min: 6, message: '密码不能少于六位数'},
                                ]
                            })(
                                <Input placeholder="请输入密码" type="password" />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="确认密码" style={{ display: 'inline-block', width: '33%' }} >
                            {getFieldDecorator('confirmPassword', {
                                rules: [{ required: true, message: '两次密码输入必须一致' },
                                    { min: 6, message: '确认密码不能少于六位数'},
                                ]
                            })(
                                <Input placeholder="请再次输入密码" type="password" />
                            )}
                        </FormItem>
                    </div>
                    <div className="related-stores">
                        <ul>
                            <li>关联门店：</li>
                            {this.state.justShowingStore.map(item=>{
                                return <li key={item}><Link to="">{item}</Link></li>
                            })}
                            <Button icon="plus" size="small" type="primary"  onClick={this.showModal2.bind(this)}>关联</Button>
                        </ul>
                    </div>
                    <div style={{maxWidth:800,textAlign:'right',marginTop:10}}>
                        <Button type='primary' style={{marginRight:15}} onClick={this.saveData}>确定</Button>
                        <Button onClick={this.cancelSave}>取消</Button>
                    </div>
                    {/*关联所属门店模态框*/}
                    <Modal footer={false}
                           title='关联所属门店'
                           visible={this.state.visible2}
                           onOk={this.handleOk2.bind(this)}
                           onCancel={this.handleCancel2.bind(this)}
                          // width={1000}
                    >
                        <Checkbox.Group style={{ width: '100%' }} value={this.state.selectedStoreList} onChange={this.handleBelongedStoreChange.bind(this)}>
                            <Row>
                                {
                                    this.state.storeNameList.map(item=>{
                                        return  <Col span={6} key={item.index}><Checkbox value={item._id}>{item.name}</Checkbox></Col>
                                    })
                                }
                            </Row>
                        </Checkbox.Group>
                        <p style={{ marginTop: 30 ,textAlign:'right'}}>
                            <Button className='member-button-aa' onClick={this.handleOk2.bind(this)} style={{ width: 100 }} type='primary'>确定</Button>
                            <Button className='member-button-aa' onClick={this.handleCancel2.bind(this)} style={{ width: 100, marginLeft: 30 }} >取消</Button>
                        </p>
                    </Modal>
                </div>
            </div>
        )
    }
}
const AddStoreForm = Form.create()(AddStore);
export default AddStoreForm;
